/**
 * 
 */
package lib.graph;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

/**
 * @author <a href="www.sureinterview.com">SureInterview</a>
 * 
 */
public class GraphAdacentLink extends Graph {
	enum G_Type {
		LINK, MATRIX
	}

	E[][] _E;
	V[] _V;
	HashMap<V, Integer> map;

	@Override
	public E[] getEs(V v) {
		List<E> es = new ArrayList<E>();

		int i = map.get(v);
		for (E e : _E[i]) {
			if (e != null) {
				es.add(e);
			}
		}
		return es.toArray(new E[es.size()]);
	}

	@Override
	public V[] getV() {
		return _V;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void load(String gStr) {
		JSONObject array = (JSONObject) JSONValue.parse(gStr);
		JSONArray arr;
		String stype = (String) array.get("type");
		G_Type type = G_Type.valueOf(stype.toUpperCase());
		if (type != G_Type.MATRIX)
			return;

		arr = (JSONArray) array.get("v");
		Integer Vlength = arr.size();

		_V = new V[Vlength];

		map = new HashMap<V, Integer>();
		for (int i = 0; i < arr.size(); i++) {
			_V[i] = new V((String) arr.get(i));
			map.put(_V[i], Integer.valueOf(i));
		}

		_E = new E[Vlength][Vlength];
		for (int i = 0; i < Vlength; i++) {
			_E[i] = new E[Vlength];
		}

		arr = (JSONArray) array.get("e");
		Iterator<JSONArray> it = arr.iterator();
		while (it.hasNext()) {
			JSONArray ja = it.next();
			int i = ((Long) ja.get(0)).intValue();
			int j = ((Long) ja.get(1)).intValue();
			int w = ((Long) ja.get(2)).intValue();
			_E[i][j] = new E(_V[i], _V[j], w);
		}
	}
}
